<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="登录名称">
        <el-input v-model="formData.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formData.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="formData.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        <el-button @click="formData = { ...$store.state.userInfo }"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  data() {
    return {
      formData: { ...this.$store.state.userInfo },
      rules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          { pattern: /^\S{1,10}$/, message: "请输入活动名称", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    updateUserInfo() {
      // 兜底校验
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "/my/userinfo",
          this.formData
        );
        // console.log(res);
        if (res.code !== 0) return this.$message.error(res.message);
        this.$message.success(res.message);
        this.$store.dispatch("initUserInfo");
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>